package repository

import (
	"context"
	"database/sql"
	"fmt"
	"strconv"
	"strings"

	"mall/common/enumx"
	"mall/common/modelx"
	"mall/service/product/model"

	"github.com/volatiletech/sqlboiler/v4/boil"
	"github.com/volatiletech/sqlboiler/v4/queries"
	"github.com/volatiletech/sqlboiler/v4/queries/qm"
	"github.com/zeromicro/go-zero/core/stores/cache"
)

type (
	// ProductTermRepository is an interface to be customized, add more methods here,
	// and implement the added methods in customProductTermRepository.
	ProductTermRepository interface {
		Conn() error
		FindOne(ctx context.Context, id int64, cols []string) (*model.ProductTerm, error) ///
		GetList(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.ProductTerm, int64, error) ///
		GetRelationshipList(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.ProductTermRelationship, int64, error) /// 根据分类或标签获取对应的文章或页面、根据文章或分页获取对应的分类和标签
		Insert(
			ctx context.Context,
			term *model.ProductTerm,
			extra *model.ProductExtra,
		) error ///
		Update(
			ctx context.Context,
			term *model.ProductTerm,
			extra *model.ProductExtra,
		) (int64, error) ///
		DeleteBatch(ctx context.Context, ids []uint64) (int64, error) ///
		GetMeta(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.ProductTermMetum, int64, error) ///
		GetMedia(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.ProductAttachmentRelationship, int64, error) ///
		IncreaseMeta(ctx context.Context, tids []int64, metaKey string, step int) (int64, error) ///
		DecreaseMeta(ctx context.Context, tids []int64, metaKey string, step int) (int64, error) ///
	}

	customProductTermRepository struct {
		cacheConf  cache.CacheConf
		dataSource string

		mysqlConn *sql.DB
	}
)

// NewProductTermRepository returns a repository for the database table.
func NewProductTermRepository(dataSource string, cacheConf cache.CacheConf) ProductTermRepository {
	return &customProductTermRepository{
		cacheConf:  cacheConf,
		dataSource: dataSource,
	}
}

func (r *customProductTermRepository) Conn() error {
	if r.mysqlConn == nil {
		mysqlConn, err := modelx.NewMysqlConn(r.dataSource)
		if err != nil {
			return err
		}

		r.mysqlConn = mysqlConn
	}

	return nil
}

func (r *customProductTermRepository) FindOne(
	ctx context.Context,
	id int64,
	cols []string,
) (term *model.ProductTerm, err error) {
	if err = r.Conn(); err != nil {
		return
	}

	term, err = model.FindProductTerm(ctx, r.mysqlConn, uint64(id), cols...)
	if err == sql.ErrNoRows {
		return nil, model.ErrNotFound
	}

	return
}

func (r *customProductTermRepository) GetList(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.ProductTerm, count int64, err error) {
	if err = r.Conn(); err != nil {
		return
	}

	var mods []qm.QueryMod
	var page int
	var pageSize int
	var offset int
	var limit int
	var selectCol string
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(int64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(int64); ok && val > 0 {
				pageSize = int(val)
			}
		case "offset":
			if val, ok := v.(int32); ok && val > 0 {
				offset = int(val)
			}
		case "limit":
			if val, ok := v.(int32); ok && val > 0 {
				limit = int(val)
			}
		case "orderBy":
			if val, ok := v.(string); ok && val != "" {
				mods = append(mods, qm.OrderBy(val))
			}
		case "select":
			if val, ok := v.(string); ok && val != "" {
				selectCol = val
			}
		}
	}

	if filter != nil {
		for key, opMap := range filter {
			switch key {
			case model.ProductTermColumns.TermID:
				mods = append(mods, modelx.GetIntMods(model.ProductTermColumns.TermID, opMap)...)
			case model.ProductTermColumns.Name:
				mods = append(mods, modelx.GetStringMods(model.ProductTermColumns.Name, opMap)...)
			case model.ProductTermColumns.Slug:
				mods = append(mods, modelx.GetStringMods(model.ProductTermColumns.Slug, opMap)...)
			case model.ProductTermColumns.Taxonomy:
				mods = append(mods, modelx.GetIntMods(model.ProductTermColumns.Taxonomy, opMap)...)
			case model.ProductTermColumns.ParentID:
				mods = append(mods, modelx.GetIntMods(model.ProductTermColumns.ParentID, opMap)...)
			case model.ProductTermColumns.TermGroup:
				mods = append(mods, modelx.GetIntMods(model.ProductTermColumns.TermGroup, opMap)...)
			case model.ProductTermColumns.Count:
				mods = append(mods, modelx.GetIntMods(model.ProductTermColumns.Count, opMap)...)
			}
		}
	}

	if withCount >= 0 {
		if withCount >= 2 {
			var nextCount int64
			var previousCount int64
			subMods := make([]qm.QueryMod, len(mods), len(mods) + 3)
			copy(subMods, mods)
			subMods = append(subMods, qm.Limit(1))
			subMods = append(subMods, qm.Select(model.ProductTermColumns.TermID))

			if withCount != 3 && offset >= 1 {
				subMods = append(subMods, qm.Offset(offset - 1))
				previousList, previousErr := model.ProductTerms(subMods...).All(ctx, r.mysqlConn)
				if previousErr != nil {
					err = previousErr
					return
				}
				if len(previousList) > 0 {
					previousCount = 1
				}
			}
			if limit > 0 {
				subMods = append(subMods, qm.Offset(offset + limit))
				nextList, nextErr := model.ProductTerms(subMods...).All(ctx, r.mysqlConn)
				if nextErr != nil {
					err = nextErr
					return
				}
				if len(nextList) > 0 {
					nextCount = 1
				}
			}

			count = previousCount + nextCount * 2
		} else {
			count, err = model.ProductTerms(mods...).Count(ctx, r.mysqlConn)
			if err != nil {
				return
			}

			if withCount == 0 {
				return
			}
		}
	}

	if pageSize > 0 {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	} else if limit > 0 || offset > 0 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit))
		}
		if offset > 0 {
			mods = append(mods, qm.Offset(offset))
		}
	}

	var columns []string
	if selectCol != "" {
		if selectCol != "," {
			columns = strings.Split(selectCol, ",")
		}
		columns = append(columns, model.ProductTermColumns.TermID)
		columns = append(columns, model.ProductTermColumns.Taxonomy)
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.ProductTerms(mods...).All(ctx, r.mysqlConn)
	return
}

func (r *customProductTermRepository) GetRelationshipList(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.ProductTermRelationship, count int64, err error) {
	if err = r.Conn(); err != nil {
		return
	}

	var mods []qm.QueryMod
	var page int
	var pageSize int
	var offset int
	var limit int
	var selectCol string
	var random bool
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(int64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(int64); ok && val > 0 {
				pageSize = int(val)
			}
		case "offset":
			if val, ok := v.(int32); ok && val > 0 {
				offset = int(val)
			}
		case "limit":
			if val, ok := v.(int32); ok && val > 0 {
				limit = int(val)
			}
		case "orderBy":
			if val, ok := v.(string); ok && val != "" {
				mods = append(mods, qm.OrderBy(val))
			}
		case "select":
			if val, ok := v.(string); ok && val != "" {
				selectCol = val
			}
		case "random":
			if val, ok := v.(string); ok && val == "1" {
				random = true
			}
		}
	}

	if filter != nil {
		for key, opMap := range filter {
			switch key {
			case model.ProductTermRelationshipColumns.TermRelationshipID:
				mods = append(mods, modelx.GetIntMods(model.ProductTermRelationshipColumns.TermRelationshipID, opMap)...)
			case model.ProductTermRelationshipColumns.ObjectID:
				mods = append(mods, modelx.GetIntMods(model.ProductTermRelationshipColumns.ObjectID, opMap)...)
			case model.ProductTermRelationshipColumns.ObjectType:
				mods = append(mods, modelx.GetIntMods(model.ProductTermRelationshipColumns.ObjectType, opMap)...)
			case model.ProductTermRelationshipColumns.TermID:
				mods = append(mods, modelx.GetIntMods(model.ProductTermRelationshipColumns.TermID, opMap)...)
			case model.ProductTermRelationshipColumns.TermOrder:
				mods = append(mods, modelx.GetIntMods(model.ProductTermRelationshipColumns.TermOrder, opMap)...)
			}
		}
	}

	if random {
		subMods := make([]qm.QueryMod, len(mods), len(mods) + 2)
		copy(subMods, mods)
		subMods = append(subMods, qm.Select(fmt.Sprintf(
			"max(%s) as max_id, min(%s) as min_id, RAND() as rand",
			model.ProductTermRelationshipColumns.ObjectID,
			model.ProductTermRelationshipColumns.ObjectID,
		)))
		subMods = append(subMods, qm.From(model.TableNames.ProductTermRelationships))

		var info RandomInfo
		// Use query building
		err = model.NewQuery(subMods...).Bind(ctx, r.mysqlConn, &info)
		if err != nil {
			return
		}

		rand := int(float64(info.MaxId - info.MinId) * info.Rand) + info.MinId
		mods = append(mods, model.ProductTermRelationshipWhere.ObjectID.GTE(uint64(rand)))
		mods = append(mods, qm.Distinct(model.ProductTermRelationshipColumns.ObjectID))

		if pageSize > 0 {
			mods = append(mods, qm.Limit(pageSize))
		}

		var columns []string
		if selectCol != "" {
			columns = strings.Split(selectCol, ",")
		}
		if len(columns) > 0 {
			mods = append(mods, qm.Select(columns...))
		}

		list, err = model.ProductTermRelationships(mods...).All(ctx, r.mysqlConn)
		return
	}

	if withCount >= 0 {
		if withCount >= 2 {
			var nextCount int64
			var previousCount int64
			subMods := make([]qm.QueryMod, len(mods), len(mods) + 3)
			copy(subMods, mods)
			subMods = append(subMods, qm.Limit(1))
			subMods = append(subMods, qm.Select(model.ProductTermRelationshipColumns.TermRelationshipID))

			if withCount != 3 && offset >= 1 {
				subMods = append(subMods, qm.Offset(offset - 1))
				previousList, previousErr := model.ProductTermRelationships(subMods...).All(ctx, r.mysqlConn)
				if previousErr != nil {
					err = previousErr
					return
				}
				if len(previousList) > 0 {
					previousCount = 1
				}
			}
			if limit > 0 {
				subMods = append(subMods, qm.Offset(offset + limit))
				nextList, nextErr := model.ProductTermRelationships(subMods...).All(ctx, r.mysqlConn)
				if nextErr != nil {
					err = nextErr
					return
				}
				if len(nextList) > 0 {
					nextCount = 1
				}
			}

			count = previousCount + nextCount * 2
		} else {
			count, err = model.ProductTermRelationships(mods...).Count(ctx, r.mysqlConn)
			if err != nil {
				return
			}

			if withCount == 0 {
				return
			}
		}
	}

	if pageSize > 0 {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	} else if limit > 0 || offset > 0 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit))
		}
		if offset > 0 {
			mods = append(mods, qm.Offset(offset))
		}
	}

	var columns []string
	if selectCol != "" {
		if selectCol != "," {
			columns = strings.Split(selectCol, ",")
		}
		columns = append(columns, model.ProductTermRelationshipColumns.TermRelationshipID)
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.ProductTermRelationships(mods...).All(ctx, r.mysqlConn)
	return
}

func (r *customProductTermRepository) Insert(
	ctx context.Context,
	term *model.ProductTerm,
	extra *model.ProductExtra,
) error {
	if err := r.Conn(); err != nil {
		return err
	}

	tx, err := r.mysqlConn.BeginTx(ctx, nil)
	if err != nil {
		return err
	}

	err = term.Insert(ctx, tx, boil.Infer())
	if err != nil {
		tx.Rollback()
		return err
	}

	if len(extra.TermMeta) > 0 {
		for _, m := range extra.TermMeta {
			m.TermID = term.TermID
			err = m.Insert(ctx, tx, boil.Infer())
			if err != nil {
				tx.Rollback()
				return err
			}
		}
	}

	if len(extra.Media) > 0 {
		for _, m := range extra.Media {
			m.ObjectID = term.TermID
			m.ObjectType = term.Taxonomy + enumx.PostTypeTermOffset
			err = m.Insert(ctx, tx, boil.Infer())
			if err != nil {
				tx.Rollback()
				return err
			}
		}
	}

	tx.Commit()
	return nil
}

func (r *customProductTermRepository) Update(
	ctx context.Context,
	term *model.ProductTerm,
	extra *model.ProductExtra,
) (int64, error) {
	if err := r.Conn(); err != nil {
		return 0, err
	}

	tx, err := r.mysqlConn.BeginTx(ctx, nil)
	if err != nil {
		return 0, err
	}

	termId, err := term.Update(ctx, tx, boil.Blacklist(
		model.ProductTermColumns.Count,
	))
	if err != nil {
		tx.Rollback()
		return 0, err
	}

	if len(extra.TermMeta) > 0 {
		for _, m := range extra.TermMeta {
			if m.MetaID > 0 {
				_, err = m.Update(ctx, tx, boil.Blacklist(
					model.ProductTermMetumColumns.MetaID,
					model.ProductTermMetumColumns.TermID,
				))
			} else {
				m.TermID = term.TermID
				err = m.Insert(ctx, tx, boil.Infer())
			}

			if err != nil {
				tx.Rollback()
				return 0, err
			}
		}
	}

	if len(extra.Media) > 0 {
		for _, m := range extra.Media {
			if m.AttachmentRelationshipID > 0 {
				_, err = m.Update(ctx, tx, boil.Blacklist(
					model.ProductAttachmentRelationshipColumns.AttachmentRelationshipID,
					model.ProductAttachmentRelationshipColumns.ObjectID,
					model.ProductAttachmentRelationshipColumns.ObjectType,
					model.ProductAttachmentRelationshipColumns.AttachmentID,
				))
			} else {
				m.ObjectID = term.TermID
				m.ObjectType = term.Taxonomy + enumx.PostTypeTermOffset
				err = m.Insert(ctx, tx, boil.Infer())
			}
			if err != nil {
				tx.Rollback()
				return 0, err
			}
		}
	}

	if len(extra.DelMetaIds) > 0 {
		ids := make([]any, 0, len(extra.DelMetaIds))
		for _, id := range extra.DelMetaIds {
			ids = append(ids, id)
		}
		var mods []qm.QueryMod
		mods = append(mods, qm.WhereIn(fmt.Sprintf("%s IN ?", model.ProductTermMetumColumns.MetaID), ids...))
		_, err := model.ProductTermMeta(mods...).DeleteAll(ctx, tx)
		if err != nil {
			tx.Rollback()
			return 0, err
		}
	}

	if len(extra.DelMediaIds) > 0 {
		ids := make([]any, 0, len(extra.DelMediaIds))
		for _, id := range extra.DelMediaIds {
			ids = append(ids, id)
		}
		var mods []qm.QueryMod
		mods = append(mods, qm.WhereIn(fmt.Sprintf("%s IN ?", model.ProductAttachmentRelationshipColumns.AttachmentRelationshipID), ids...))
		_, err := model.ProductAttachmentRelationships(mods...).DeleteAll(ctx, tx)
		if err != nil {
			tx.Rollback()
			return 0, err
		}
	}

	tx.Commit()
	return termId, nil
}

func (r *customProductTermRepository) DeleteBatch(ctx context.Context, ids []uint64) (rowsAff int64, err error) {
	if err = r.Conn(); err != nil {
		return
	}

	if len(ids) > 0 {
		var mods []qm.QueryMod
		values := make([]any, 0, len(ids))
		for _, id := range ids {
			values = append(values, id)
		}
		mods = append(mods, qm.WhereIn(fmt.Sprintf("%s IN ?", model.ProductTermColumns.TermID), values...))
		rowsAff, err = model.ProductTerms(mods...).DeleteAll(ctx, r.mysqlConn)
	}

	return
}

func (r *customProductTermRepository) GetMeta(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.ProductTermMetum, count int64, err error) {
	if err = r.Conn(); err != nil {
		return
	}

	var mods []qm.QueryMod
	var page int
	var pageSize int
	var selectCol string
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(int64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(int64); ok && val > 0 {
				pageSize = int(val)
			}
		case "orderBy":
			if val, ok := v.(string); ok && val != "" {
				mods = append(mods, qm.OrderBy(val))
			}
		case "select":
			if val, ok := v.(string); ok && val != "" {
				selectCol = val
			}
		}
	}

	if filter != nil {
		for key, opMap := range filter {
			switch key {
			case model.ProductTermMetumColumns.MetaID:
				mods = append(mods, modelx.GetIntMods(model.ProductTermMetumColumns.MetaID, opMap)...)
			case model.ProductTermMetumColumns.TermID:
				mods = append(mods, modelx.GetIntMods(model.ProductTermMetumColumns.TermID, opMap)...)
			case model.ProductTermMetumColumns.MetaKey:
				mods = append(mods, modelx.GetStringMods(model.ProductTermMetumColumns.MetaKey, opMap)...)
			}
		}
	}

	if withCount >= 0 {
		count, err = model.ProductTermMeta(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}
	}

	if pageSize > 0 {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	}

	var columns []string
	if selectCol != "" {
		if selectCol != "," {
			columns = strings.Split(selectCol, ",")
		}
		columns = append(columns, model.ProductTermMetumColumns.MetaID)
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.ProductTermMeta(mods...).All(ctx, r.mysqlConn)
	return
}

func (r *customProductTermRepository) GetMedia(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.ProductAttachmentRelationship, count int64, err error) {
	if err = r.Conn(); err != nil {
		return
	}

	var mods []qm.QueryMod
	var page int
	var pageSize int
	var selectCol string
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(int64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(int64); ok && val > 0 {
				pageSize = int(val)
			}
		case "orderBy":
			if val, ok := v.(string); ok && val != "" {
				mods = append(mods, qm.OrderBy(val))
			}
		case "select":
			if val, ok := v.(string); ok && val != "" {
				selectCol = val
			}
		}
	}

	if filter != nil {
		for key, opMap := range filter {
			switch key {
			case model.ProductAttachmentRelationshipColumns.AttachmentRelationshipID:
				mods = append(mods, modelx.GetIntMods(model.ProductAttachmentRelationshipColumns.AttachmentRelationshipID, opMap)...)
			case model.ProductAttachmentRelationshipColumns.ObjectID:
				mods = append(mods, modelx.GetIntMods(model.ProductAttachmentRelationshipColumns.ObjectID, opMap)...)
			case model.ProductAttachmentRelationshipColumns.ObjectType:
				mods = append(mods, modelx.GetIntMods(model.ProductAttachmentRelationshipColumns.ObjectType, opMap)...)
			case model.ProductAttachmentRelationshipColumns.AttachmentID:
				mods = append(mods, modelx.GetIntMods(model.ProductAttachmentRelationshipColumns.AttachmentID, opMap)...)
			case model.ProductAttachmentRelationshipColumns.AttachmentThumbnail:
				mods = append(mods, modelx.GetIntMods(model.ProductAttachmentRelationshipColumns.AttachmentThumbnail, opMap)...)
			case model.ProductAttachmentRelationshipColumns.AttachmentOrder:
				mods = append(mods, modelx.GetIntMods(model.ProductAttachmentRelationshipColumns.AttachmentOrder, opMap)...)
			}
		}
	}

	if withCount >= 0 {
		count, err = model.ProductAttachmentRelationships(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}
	}

	if pageSize > 0 {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	}

	var columns []string
	if selectCol != "" {
		if selectCol != "," {
			columns = strings.Split(selectCol, ",")
		}
		columns = append(columns, model.ProductAttachmentRelationshipColumns.AttachmentRelationshipID)
		columns = append(columns, model.ProductAttachmentRelationshipColumns.ObjectID)
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.ProductAttachmentRelationships(mods...).All(ctx, r.mysqlConn)
	return
}

func (r *customProductTermRepository) IncreaseMeta(ctx context.Context, tids []int64, metaKey string, step int) (rowsAff int64, err error) {
	if err = r.Conn(); err != nil {
		return
	}

	if len(tids) > 0 {
		termIds := make([]string, 0, len(tids))
		for _, tid := range tids {
			termIds = append(termIds, strconv.FormatInt(tid, 10))
		}
		var info RandomInfo
		err = queries.Raw(fmt.Sprintf(
			`update %s set %s=%s+%d where %s="%s" and %s in (%s)`,
			model.TableNames.ProductTermMeta,
			model.ProductTermMetumColumns.MetaValue,
			model.ProductTermMetumColumns.MetaValue,
			step,
			model.ProductTermMetumColumns.MetaKey,
			metaKey,
			model.ProductTermMetumColumns.TermID,
			strings.Join(termIds, ","),
		)).Bind(ctx, r.mysqlConn, &info)

		if err == sql.ErrNoRows {
			return 0, model.ErrNotFound
		}
	}

	return
}

func (r *customProductTermRepository) DecreaseMeta(ctx context.Context, tids []int64, metaKey string, step int) (rowsAff int64, err error) {
	if err = r.Conn(); err != nil {
		return
	}

	if len(tids) > 0 {
		termIds := make([]string, 0, len(tids))
		for _, tid := range tids {
			termIds = append(termIds, strconv.FormatInt(tid, 10))
		}
		var info RandomInfo
		err = queries.Raw(fmt.Sprintf(
			`update %s set %s=%s-%d where %s="%s" and %s in (%s)`,
			model.TableNames.ProductTermMeta,
			model.ProductTermMetumColumns.MetaValue,
			model.ProductTermMetumColumns.MetaValue,
			step,
			model.ProductTermMetumColumns.MetaKey,
			metaKey,
			model.ProductTermMetumColumns.TermID,
			strings.Join(termIds, ","),
		)).Bind(ctx, r.mysqlConn, &info)

		if err == sql.ErrNoRows {
			return 0, model.ErrNotFound
		}
	}

	return
}
